#include <algorithm>
#include "Graph.h"

namespace Audio
{
	Graph::Graph(std::string name)
	///////////////////////////////////////////////////////////////////////////////
	// Description: Constructs the graph.  Min and max are the first and last Y
	//				values in the point list
	//
	// Recent Changes:
	// -brasmuss 3/30/2007 : Created
	///////////////////////////////////////////////////////////////////////////////
	{
		m_name	 = name;
		m_min    = 0.0f;
		m_max    = 1.0f;
	}

	float Graph::Compute(float input)
	///////////////////////////////////////////////////////////////////////////////
	// Description: Interpolates between keyframes and returns the output value
	//
	// Recent Changes:
	// -brasmuss 3/30/2007 : Created
	///////////////////////////////////////////////////////////////////////////////
	{
		if(m_points.size() < 2 || input < m_min || input > m_max)
			return 0.0f;

		if(input == m_points[0].m_x)
			return m_points[0].m_y;
		if(input == m_points[m_points.size()-1].m_x)
			return m_points[m_points.size()-1].m_y;

		// Figure out which key-frames I am between
		unsigned before = 0;
		while(m_points[before+1].m_x < input)
			++before;
		unsigned after = before + 1;
		float perc = (input - m_points[before].m_x) / (m_points[after].m_x - m_points[before].m_x);
		float output = m_points[before].m_y + perc*(m_points[after].m_y - m_points[before].m_y);
		return output;
	}

	void Graph::AddPoint(float x, float y)
	{
		m_points.push_back(Point(x,y));
	}

	void Graph::SortPoints()
	{
		std::sort(m_points.begin(),m_points.end());
	}
}